package com.teemor.common.bean.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/3/26
 */
public class IPInfoUtils {

    private static final String BASE_URI = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=";

    public static String getIpaddr(RestTemplate restTemplate, String ip) {
        String url = BASE_URI + ip;
        String res = restTemplate.getForObject(url, String.class);
        Map<?, ?> map = BeanConvertor.objectToMap(JSONObject.parseObject(res));
        if (CollectionUtils.isEmpty(map)) {
            return null;
        }
        return map.get("pro") + "/" + map.get("city");
    }

    public static String getIp(ServerHttpRequest request) {
        HttpHeaders header = request.getHeaders();
        String ip = header.getFirst("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = header.getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = header.getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = header.getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = header.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = header.getFirst("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
        }
        return ip;
    }
}
